NestJS REST API
REST 是一种 API 架构模式
REST 核心架构原则
- 无状态性(Statelessness):每个请求应包含所有必要信息,服务器不保存客户端状态
- 资源导向(Resource-Oriented):API 围绕资源而非动作设计
- 统一接口(Uniform Interface):使用标准 HTTP 方法(GET, POST, PUT, PATCH, DELETE)
shell
GET: 获取资源
POST: 创建资源
PUT: 更新整个资源
PATCH: 部分更新资源
DELETE: 删除资源在项目中使用 RESTful API 示例
- 定义默认路由 api/v1 片段
ts
// src/main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix('api/v1');
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();- 定义 GET, POST, PUT, PATCH, DELETE 方法,获取 http 参数
所有方法:GET, POST, PUT, PATCH, DELETE
所有参数:params、query、body、request(所有参数:包含前三者)
ts
// src/app.controller.ts
import { Controller, Get, Post, Put, Delete, Param, Body, Query, Request } from '@nestjs/common';
import { AppService } from './app.service';
@Controller('/test')
export class AppController {
constructor(private readonly appService: AppService) {}
// get 获取 param 参数,http://localhost:3000/api/v1/test/100
@Get(':id')
findOne(@Param('id') id: string): any {
return {
message: '获取 param 参数',
data: {
id,
},
};
}
// get 获取 query 参数
@Get()
findAll(@Query() query: any): any {
return {
message: '获取 query 参数',
data: {
query,
},
};
}
// post 获取 body 参数
@Post()
create(@Body() body: any): any {
return {
message: '获取 body 参数',
data: {
body,
},
};
}
// post 获取 request 参数(包含:param、query、body)
@Post('/all/:id')
getAllParam(@Request() request: any): any {
const { query, params, body } = request;
return {
message: '获取 request 参数',
data: { query, params, body },
};
}
// put 获取 body 参数
@Put()
update(@Body() body: any): any {
return {
message: '获取 body 参数',
data: {
body,
},
};
}
// delete 获取 param 参数
@Delete(':id')
remove(@Param('id') id: string): any {
return {
message: '获取 body 参数',
data: {
param: { id },
},
};
}
}- 在 Apifox 调试工具中调试,在请求路径相同的情况下,可通过不同的 http 方法来定位不同路由
shell
http://localhost:3000/api/v1/test @Get装饰器 当请求方法为 GET 时,访问本路由
http://localhost:3000/api/v1/test @Post装饰器 当请求方法为 POST 时,访问本路由
http://localhost:3000/api/v1/test @Put装饰器 当请求方法为 PUT 时,访问本路由
http://localhost:3000/api/v1/test @Delete装饰器 当请求方法为 DELETE 时,访问本路由